import {
  type RouteRecordRaw,
  createRouter,
  createWebHistory,
  RouteLocationNormalized,
  NavigationGuardNext
} from "vue-router"

const componentBaseUrl = "/src/views"
const modules = import.meta.glob("@/views/**/*.vue")

const routes: RouteRecordRaw[] = [
  // {
  //   redirect: "/login",
  //   path: "/",
  //   component: () => import("../views/index.vue"),
  //   name: "index",
  //   children: []
  // },el
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/index.vue")
  },
  {
    path: "/webRtc",
    name: "webRtc",
    component: () => import("../views/webRtc/index.vue")
  },
  {
    path: "/",
    name: "layout",
    component: () => import("@/views/layout/index.vue")
  },
  {
    path: "/fabric",
    name: "fabric",
    component: () => import("@/views/fabric/index.vue")
  },
  // 404页面
  {
    path: "/:pathMatch(.*)*",
    component: () => import("../views/404.vue")
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

function getComponentName(str: string) {
  return str
    .replace(/(\/(.))/g, ($1: any) => {
      return $1.split("/")[1].toUpperCase()
    })
    .split(".")[0]
}
const whiteList = ["/login", "/fabric"]

router.beforeEach(async (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  if (!router.hasRoute(to.name as string)) {
    const vuePath = `${componentBaseUrl}${to.path}.vue`
    router.addRoute("layout", {
      path: to.path,
      name: getComponentName(to.path),
      component: modules[vuePath] || (() => import("../views/error/404.vue"))
    })
    next({ path: to.path, replace: true })
    return
  } else {
    next()
  }

  // const userInfo: any = JSON.parse(window.localStorage.getItem("userInfo") as string)
  // console.log(userInfo?.token, "d")
  // if (!userInfo?.token && to.path != "/login") {
  //   next("/login")
  // } else {
  //   if (userInfo?.token) {
  //     if (to.path == "/login") {
  //       next("/index")
  //     }
  //     next()
  //   }
  //   next()
  // }
})
export default router
